<template>
  <div class="ky-container">
    <div @click="closeRight">
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg" v-show="!isExtend">
        <el-form ref="form" :model="formData" :inline="true" class="ky-form-inline ky-form-inline-sm" label-width="80px">
          <el-form-item label="医院名称" prop="hospitalCode">
            <el-select size="small" class="param-type_input" v-model="formData.hospitalCode" @change="handleChange('hospital')" placeholder="请选择" filterable>
              <el-option v-for="(item,index) in mx_hospitalList" :key="index" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="院区">
            <el-select style="width: 140px;" size="mini" v-model="formData.areaName" clearable placeholder="院区" @change="areaNameChange">
              <el-option
                v-for="(item, index) in areaNameOptions"
                :key="index"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型">
            <el-select label="参数类型" size="small" class="param-type_input" style="width: 120px;" v-model="formData.ParameterType" placeholder="请选择" filterable clearable>
              <el-option v-for="(item,index) in ParameterTypeOptions" :key="index" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="IP">
            <el-input
              size="small"
              v-model.trim="formData.IpAddress"
              placeholder="IP地址如192.168.0.1"
              clearable
              style="width: 170px;"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="m-l-0 click-button" size="small" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="m-l-0 click-button" size="small" @click="resetParam" plain>重置</el-button>
            <el-button
              type="primary"
              size="small"
              @click.stop="getRightPanel('add')"><i class="el-icon-plus icon"></i> 新增</el-button>
            <el-button v-if="false" :type="isSortUp ? 'success':'warning'" size="small" @click.stop="sortData()"><i :class="isSortUp ? 'el-icon-sort-up':'el-icon-sort-down'"></i> {{isSortUp ? '正序' : '倒序'}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg content-height ky-mt10">
        <div class="content-title flex flex-row align-end">
          <span class="fs-16 font-bold">客户端参数列表</span>
          <span class="fs-13 mar-l-5">当前电脑IP:{{clientIP}}</span>
          <!-- <span style="color: red;font-size: 14px;float: left;">【勾选任意一项支持批量启用,禁用,删除】</span> -->
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          size="medium"
          :data="tableData"
          style="width: 100%"
          border
          class="ky-table"
          highlight-current-row>
          <!-- <el-table-column type="selection" width="55"></el-table-column> -->
          <el-table-column align="center" fixed label="操作" width="200">
            <template slot-scope="scope">
              <div class="flex flex-row justify-center">
                <el-button type="primary" size="small" @click.stop="getRightPanel('edit', scope.row)"><i class="el-icon-edit"></i> 查看或编辑</el-button>
                <el-button type="danger" size="small" @click.stop="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete"></i> 删除</el-button>
                <!-- <el-button type="primary" size="small"><i class="el-icon-edit"></i> 参数配置</el-button> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="areaName" label="院区" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="parameterType" label="参数类型" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="ipRange" label="IP地址范围" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" prop="remark" label="备注说明" show-overflow-tooltip></el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="changePagination"
        />
      </el-card>
      <!-- <transition name="fade-form" mode="out-in">
        <div :class="{'toolBox-small':device !== 'mobile' && sidebar.opened,'toolBox-midul': device !== 'mobile' && !sidebar.opened,'toolBox-large':device == 'mobile','toolBox':true}" v-show="showToolBox">
          <div>
            <i class="el-icon-info icon blue-color"></i>
            <span class="toolBox-text">已选择<span class="blue-color">{{multipleSelection.length}}</span>项</span>
            <span class="cancle-click" @click="cancleChoose">取消选择</span>
          </div>
          <div>
            <el-button type="warning" size="small" v-if="onFlag&&!offFlag" @click="batchSetStatus">批量禁用</el-button>
            <el-button type="success" size="small" v-else-if="!onFlag&&offFlag" @click="batchSetStatus">批量启用</el-button>
            <el-button type="danger" size="small" @click="batchDelete">批量删除</el-button>
          </div>
        </div>
      </transition> -->
    </div>
    <edit
      ref="edit"
      :hospital-code.sync="formData.hospitalCode"
      :areaname.sync="formData.areaName"
      :show-right.sync="showRight"
      :row-data.sync="rowData"
      :title.sync="title"
      :cur-status="curStatus"
      @refresh="search"
    ></edit>
  </div>
</template>
<script>
// import { getItemListFunc } from '@/api/common'
import { mapGetters } from 'vuex'
import edit from './edit'
import paginationCont from '@/components/Pagination/index'
import {
  deleteClientParam,
  getClientParamPages
} from '@/api/api.js'
export default {
  name: '',
  components: {
    paginationCont,
    edit
  },
  created() {
    this.$getHospitalList()
    this.getAreaNameList()
  },
  data() {
    return {
      isExtend: 0,
      formData: {
        hospitalCode: this.$store.state.user.hospitalCode,
        areaName: '',
        ParameterType: '',
        IpAddress: ''
      },
      isSortUp: false,
      ParameterTypeOptions: ['医技Web', '临床Web'],
      multipleSelection: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      tableData: [],
      showToolBox: false,
      onFlag: false,
      offFlag: false,
      showRight: false,
      title: '',
      curStatus: '',
      rowData: {}
    }
  },
  computed: {
    ...mapGetters(['areaNameOptions', 'clientIP']),
    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    }
  },
  watch: {
    multipleSelection(val) {
      if (val && val.length >= 1) {
        this.showToolBox = true
        this.onFlag = false
        this.offFlag = false
        val.forEach(el => {
          if (el.isOpen === 'True') {
            this.onFlag = true
          } else {
            this.offFlag = true
          }
        })
      } else {
        this.showToolBox = false
      }
    }
  },
  mounted() {
    // this.formData.hospitalCode = this.$store.state.user.hospitalCode || ''
    try {
      this.search()
    } catch (err) {
      console.log(err)
    }
    // this.getUserIP()
  },
  methods: {
    // getUserIP() {
    //   fetch('https://api.ipify.org?format=json').then(response => response.json()).then(data => {
    //     // this.ip = data.ip;
    //     console.log('data', data)
    //   }).catch(error => {
    //     console.error('获取IP地址失败:', error)
    //     // this.ip = '无法获取'
    //   })
    // },
    // 切换院区
    async areaNameChange() {
      await this.getAreaNameList()
    },
    // 获取院区列表
    async getAreaNameList() {
      let params = { HospitalCode: this.formData.hospitalCode }
      await this.$store.dispatch('settings/set_areaNameOptions', params)
    },
    // getDepOptions() {
    //   const params = {
    //     hospitalCode: this.formData.hospitalCode
    //   }
    //   return new Promise(resolve => {
    //     getDepList(params).then(res => {
    //       if (res.code === 10000) {
    //         this.depOptions = res.content.list
    //         resolve(res)
    //       }
    //     })
    //   })
    // },
    changePagination() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.fetchData()
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    search() {
      console.log('刷新search')
      this.loading = true
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      console.log('fetch()')
      this.loading = true
      let data = {
        HospitalCode: this.formData.hospitalCode,
        ParameterType: this.formData.ParameterType,
        AreaName: this.formData.areaName,
        IpAddress: this.formData.IpAddress,
        // sortOrder: 'Desc',
        // sortName: 'CreateTime',
        PageSize: this.pageSize, // 页面大小
        PageNumber: this.currentPage // 页码
      }
      console.log('data', data)
      console.log('getClientParamPages-before')
      getClientParamPages(data).then(res => {
        console.log('getClientParamPages-in')
        this.loading = false
        if (res.code === 10000) {
          this.tableData = res.content.list
          this.totalCount = res.content.totalCount
          // console.error('this.tableData', this.tableData)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    handleDelete(i, row) {
      let confirmMsg = '此操作将永久删除该客户端配置, 是否继续?'
      if (this.rowData) {
        confirmMsg = '此操作将永久删除该客户端配置, 是否继续?'
      }
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteData(row) {
      let param = {
        hospitalCode: this.formData.hospitalCode,
        id: row.id
      }
      deleteClientParam(param).then((res) => {
        if (res.code === 10000) {
          this.$message.success('删除成功')
          this.showRight = false
          this.changePagination()
          // 本地缓存排班管理的机房选择数据重置默认选项
          // this.$store.dispatch('user/getDefaultCheckRoomTree')
          // this.$store.dispatch('user/resetDefaultCheckRoom', [])
        }
      })
    },
    resetParam() {
      console.log('resetParam')
      // 重置
      const resetForm = {
        hospitalCode: this.$store.state.user.hospitalCode,
        areaName: '',
        ParameterType: '',
        IpAddress: ''
      }
      this.formData = Object.assign(this.formData, resetForm)
      // this.getDepOptions()
    },
    // 获取右边form
    getRightPanel(status, params) {
      this.curStatus = status
      this.$refs.table.setCurrentRow(params)
      if (params) {
        this.rowData = params
        this.title = '编辑客户端参数'
      } else {
        this.title = '新增客户端参数'
        this.rowData = null
      }
      this.showRight = true
      this.$refs.edit.resetDialog()
      console.log('showRight')
      // 需调用弹窗里的重置
      // this.$nextTick(() => {
      //   this.$refs.edit.setDefaultFormData()
      // }, 200)
    },
    handleChange(val) {
      switch (val) {
        case 'hospital':
          this.resetParam()
          this.tableData = []
          this.totalCount = 0
          try {
            // this.getDepOptions()
            // this.getMessageType()
            this.search()
          } catch (err) {
            console.log(err)
          }
          break
        default:
          break
      }
    },
    closeRight() {
      this.showRight = false
    },
    sortData() {
      this.loading = true
      this.formData.sortOrder = this.isSortUp ? 'ASC' : 'DESC'
      this.isSortUp = !this.isSortUp
      this.fetchData()
    }
  }
}
</script>
<style lang='scss' scoped>
  .ky-container{
      .content-title{
          margin-bottom: 10px;
          span{
              font-family: PingFangSC-Medium, PingFang SC;
          }
          .add-button{
              width: 96px;
              height: 32px;
              margin-left: 16px;
          }
      }
      .toolBox{
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-top: 1px solid #E5E7EC;
          padding: 12px 28px;
          position: fixed;
          bottom: 0;
          background: #fff;
          z-index: 10;
          margin-left: -20px;
          .toolBox-text{
              margin-left: 8px;
              font-size: 13px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.65);
              span{
                  margin:0 4px;
              }
          }
          .cancle-click{
              cursor: pointer;
              font-size: 13px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #919398;
              margin-left: 32px;
          }
    }
    .toolBox-small{
        width: calc(100% - 210px);
    }
    .toolBox-midul{
        width: calc(100% - 54px);
    }
    .toolBox-large{
        width: 100%
    }
  }
  .btn_right_setting{
      /* position: absolute; */
      /* right: 6px; */
      /* top: 2px; */
      /* right: 20px; */
      /* bottom: 2px; */
      margin-top: -5px;
      width: 65px;
      /* float: right; */
      float: left;
      /* z-index: 1000; */
  }
  .content-height >>> .el-card__body {
    min-height: 704px;
    /* max-height: 800px; */
  }
</style>
